package util;

import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.json.simple.JSONObject;

import model.Teacher;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Sender;

public class DeviceNotifier {

    private final static Executor threadPool = Executors.newFixedThreadPool(5);

    public static void notify(ArrayList<String> devices, Teacher teacher, boolean absent) {

        Sender sender = new Sender("AIzaSyAQuZzD1x-33GSdfeq14Vgs7xfhrrFhBiY");
        Message gcmMessage = new Message.Builder().collapseKey("1").timeToLive(3).delayWhileIdle(true).addData("message", generateXMLString(teacher, absent)).build();

        threadPool.execute(new DeviceNotifier.Notifier(sender, gcmMessage, devices));
    }

    @SuppressWarnings("unchecked")
    private static String generateXMLString(Teacher teacher, boolean absent) {

        JSONObject obj = new JSONObject();
        obj.put("name", teacher.getName());
        obj.put("code", teacher.getCode());
        obj.put("absent", absent);

        return obj.toJSONString();
    }

    public static class Notifier implements Runnable {

        private Sender sender;
        private Message gcmMessage;
        private ArrayList<String> devices;

        public Notifier(Sender sender, Message gcmMessage, ArrayList<String> devices) {

            this.sender = sender;
            this.gcmMessage = gcmMessage;
            this.devices = devices;
        }

        @Override
        public void run() {

            try {
                sender.send(gcmMessage, devices, 1);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
